<template>
	<view class="content">
		<uv-steps :current="current" direction="column" active-color="#0C377B">
			<uv-steps-item iconSize="60rpx" customStyle="padding-bottom: 80rpx;">
				<template v-slot:title>
					<text class="cardTitel">连接蓝牙</text>
				</template>
				<template v-slot:desc>
					<!-- <text class="cardDesc">{{openBULE?'':'未打开蓝牙'}}</text> -->
					<image v-if="current ==0" src="../../static/scan.png"
						style="width: 100rpx;margin: 40rpx 0 0 100rpx;" mode="widthFix" @click="scan">
					</image>
				</template>
			</uv-steps-item>
			<uv-steps-item iconSize="60rpx" customStyle="padding-bottom: 80rpx;">
				<template v-slot:title>
					<text class="cardTitel">设置型号</text>
				</template>
				<template v-slot:desc>
					<view class="cardDesc" style="padding-top: 40rpx;">
						<uv-input suffixIcon="arrow-down" suffixIconStyle="color: #909399;" disabled v-model="bedLK"
							@click="change"></uv-input>

					</view>
					<view class="cardDesc" style="margin-top: 20rpx;">
						<uv-button type="primary" :plain="true" :hairline="true" text="设置" :custom-style="customStyle"
							@click="setting" :disabled="disabled"></uv-button>
					</view>

				</template>
			</uv-steps-item>
			<uv-steps-item iconSize="60rpx" customStyle="padding-bottom: 120rpx;">
				<template v-slot:title>
					<text class="cardTitel">wifi联网测试</text>
				</template>
				<template v-slot:desc>
					<view class="cardDesc">
						<view style="margin-top: 20rpx;">
							账号：<uv-input v-model="wifiName">
								<template v-slot:suffix>
									<image src="/static/mtz/refreshWifi.png" style="width: 32rpx;height: 32rpx;" mode=""
										@click="setUp"></image>
								</template>
							</uv-input>

						</view>
						<view style="margin-top: 20rpx;">
							密码：<uv-input v-model="wifiPass">

							</uv-input>
						</view>
						<view style="margin-top: 20rpx;">
							<uv-button type="primary" :custom-style="customStyle" :plain="true" :hairline="true"
								text="联网" @click="submit" :disabled="disabled"></uv-button>
						</view>
					</view>
				</template>
			</uv-steps-item>
			<uv-steps-item iconSize="60rpx">
				<template v-slot:title>
					<text class="cardTitel">测试完成</text>
				</template>
				<template v-slot:desc>
					<view class="cardDesc">
						<view style="margin-top: 20rpx;">
							<uv-button type="primary" :custom-style="customStyle" :plain="true" :hairline="true"
								text="完成" @click="cleanSetting" :disabled="disabled"></uv-button>
						</view>
					</view>
				</template>
			</uv-steps-item>
		</uv-steps>
		<uv-picker ref="picker" :columns="columns" @confirm="confirm"></uv-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		toRefs,
		reactive,
		computed,
		watch,
		onMounted,
		onUnmounted,
		onActivated,
		onDeactivated,
		getCurrentInstance
	} from "vue";
	import {
		useStore
	} from 'vuex';
	import {
		onLoad,
		onShow,
		onReady,
		onUnload,
		onHide
	} from '@dcloudio/uni-app'
	import {
		openBluetoothAdapter,
		startBluetoothDevicesDiscovery,
		formatMacAddress,
		getBLEDeviceServices,
		getBLEDeviceCharacteristics,
		ut_fn_time16,
		writeBLECharacteristicValue,
		sendToBLE,
		ab2hexNew,
		notifyBLECharacteristicValueChange,
		str_to_hex,
		closeBLEConnection
	} from '@/utils/bluteMethod.js'
	import {
		writeSmartBed
	} from "@/utils/bluteWrite.js";
	const store = useStore()
	const deviceMac = computed(() => store.state.deviceMac)
	const current = ref(0)
	const disabled = ref(false)
	const openBULE = ref(false)
	const macShow = ref(false)
	const wifiName = ref('')
	const wifiPass = ref('')
	const deviceMAC = ref()
	const bedLK = ref('K10')
	const picker = ref()
	const wififangwen = ref([])
	const deviceOBj = computed(() => store.state.deviceOBj)
	const settingTime = ref(0)
	const columns = [
		['K10', 'K11', 'K12']
	]
	onLoad(() => {
		openBlue()
		uni.onBLECharacteristicValueChange(async (res) => {
			let decimalNumber = ab2hexNew(res.value);
			wififangwen.value.push(decimalNumber)
			if (settingTime.value == 2) {
				disabled.value = false
			} else if (settingTime.value == 3) {
				if (wififangwen.value.every(item => item === 13) && wififangwen.value.length === 3) {
					disabled.value = false
				} else if (wififangwen.value.length === 3 && !wififangwen.value.every(item => item ===13)) {
					disabled.value = false;
					uni.showToast({
						icon:'none',
						title:'联网失败请重试'
					})
				}
			}

		});
	})
	const openBlue = async () => {
		openBULE.value = await openBluetoothAdapter()
	}

	const setting = () => {
		wififangwen.value = []
		if (deviceMac.value && current.value == 1) {
			disabled.value = true
			if (Object.keys(deviceOBj.value).length > 0) {
				sendToBLE(deviceMac.value, bedLK.value == "K10" ? 5 : bedLK.value == "K11" ? 6 : 7, null, deviceOBj
					.value);
			} else {
				blueone(5)
			}
			settingTime.value = 2
		} else {
			uni.showToast({
				icon: 'none',
				title: '蓝牙未连接'
			})
		}


	}
	const scan = () => {
		uni.scanCode({
			success: (res) => {
				const result = JSON.parse(res.result)
				if (result?.devMAC) {
					deviceMAC.value = formatMacAddress(result?.devMAC)
					setTimeout(() => {
						startBluetoothDevicesDiscovery(deviceMAC.value)
					}, 500)
				}

			}
		});
	}
	const cleanSetting = async () => {
		if (Object.keys(deviceOBj.value).length > 0) {
			let writeBLECharact = await sendToBLE(deviceMac.value, 8, null, deviceOBj.value);
			if (writeBLECharact) {
				store.commit('updateBLEConnectobj', {});
				closeBLEConnection(deviceMac.value)
				settingTime.value = 0
				current.value = 0
				deviceOBj.value = {}
				deviceMac.value = ''
				bedLK.value = 'K10'
				wifiName.value = ''
				wifiPass.value = ''
				wififangwen.value = []

			}
		} else {
			store.commit('updateBLEConnectobj', {});
			closeBLEConnection(deviceMac.value)
			settingTime.value = 0
			current.value = 0
			deviceOBj.value = {}
			deviceMac.value = ''
			bedLK.value = 'K10'
			wifiName.value = ''
			wifiPass.value = ''
			wififangwen.value = []
		}

	}
	const change = () => {
		picker.value.open()
	}
	const confirm = (e) => {
		bedLK.value = e.value
	}
	const customStyle = computed(() => {
		return {
			height: '70rpx',
			width: '160rpx',
		};
	});
	const submit = async () => {
		wififangwen.value = []
		if (deviceMac.value) {
			if (Object.keys(deviceOBj.value).length > 0) {
				if (!wifiName.value.length && !wifiPass.value.length) {
					uni.showToast({
						title: '请输入wifi账号以及密码',
						icon: 'none'
					})
				} else if (!wifiName.value.length) {
					uni.showToast({
						title: '请输入wifi账号',
						icon: 'none'
					})
				} else if (!wifiPass.value.length) {
					uni.showToast({
						title: '请输入wifi密码',
						icon: 'none'
					})
				} else {
					disabled.value = true
					let code = ut_fn_time16(new Date().getTime());
					let writeBLECharact = await writeBLECharacteristicValue({
						...deviceOBj.value,
						writeCode: `0x550xAA0x0B${code}`,
					})
					if (writeBLECharact) {
						const hexCharname = await str_to_hex(wifiName.value)
						const hexCharpass = await str_to_hex(wifiPass.value)
						const wifiNameObj = {
							wifinamelength: calculateHexBytes(hexCharname),
							hexCharname: `${hexCharname}0x00`
						}
						const wifiPassObj = {
							wifinamelength: calculateHexBytes(hexCharpass),
							hexCharname: `${hexCharpass}0x00`
						}
						const sendwifiname = await handleSendName(wifiNameObj);
						const sendwifipass = await handleSendPass(wifiPassObj);
						const sendwifilink = await handleSendwifi(wifiPassObj);
						settingTime.value = 3
					}


				}
			} else {
				if (!wifiName.value.length && !wifiPass.value.length) {
					uni.showToast({
						title: '请输入wifi账号以及密码',
						icon: 'none'
					})
				} else if (!wifiName.value.length) {
					uni.showToast({
						title: '请输入wifi账号',
						icon: 'none'
					})
				} else if (!wifiPass.value.length) {
					uni.showToast({
						title: '请输入wifi密码',
						icon: 'none'
					})
				} else {
					disabled.value = true
					blueone(6)
					settingTime.value = 3
				}

			}
		} else {
			uni.showToast({
				icon: 'none',
				title: '蓝牙未连接'
			})
		}
	}
	const valueChangeListener = ref(null)
	const blueone = async (type) => {
		let servise = await getBLEDeviceServices(deviceMac.value)
		let characteristicId = await getBLEDeviceCharacteristics({
			deviceId: deviceMac.value,
			serviceId: servise.uuid,
		})
		if (characteristicId) {
			let code = ut_fn_time16(new Date().getTime());
			let deviceOBj = {
				deviceId: deviceMac.value,
				serviceId: servise.uuid,
				characteristicId: characteristicId.uuid,
			}

			store.commit('updateBLEConnectobj', deviceOBj);
			if (type == 6) {
				let writeBLECharact = await writeBLECharacteristicValue({
					...deviceOBj,
					writeCode: `0x550xAA0x0B${code}`,
				})
				if (writeBLECharact) {
					const hexCharname = await str_to_hex(wifiName.value)
					const hexCharpass = await str_to_hex(wifiPass.value)
					const wifiNameObj = {
						wifinamelength: calculateHexBytes(hexCharname),
						hexCharname: `${hexCharname}0x00`
					}
					const wifiPassObj = {
						wifinamelength: calculateHexBytes(hexCharpass),
						hexCharname: `${hexCharpass}0x00`
					}
					const sendwifiname = await handleSendName(wifiNameObj);
					const sendwifipass = await handleSendPass(wifiPassObj);
					const sendwifilink = await handleSendwifi(wifiPassObj);
				}
			}
			if (type == 5) {
				sendToBLE(deviceMac.value, bedLK.value == "K10" ? 5 : bedLK.value == "K11" ? 6 : 7, null,
					deviceOBj);
			}
			notifyBLECharacteristicValueChange({
				deviceId: deviceMac.value,
				serviceId: servise.uuid,
				characteristicId: '0000FF02-0000-1000-8000-00805F9B34FB',
			})

			return deviceOBj
		}

	}
	const calculateHexBytes = (hexString) => {
		let hexStringL = `${hexString}0x00`
		let cleanHex = hexStringL.replace(/0x/g, '').replace(/\s+/g, '');
		if (!/^[0-9A-Fa-f]+$/.test(cleanHex)) {
			throw new Error('Invalid hex string');
		}
		// 计算字节数  
		let byteCount = cleanHex.length / 2;
		let byteCountHex = byteCount.toString(16).toUpperCase();
		if (byteCountHex.length < 2) {
			byteCountHex = '0' + byteCountHex;
		}
		return byteCountHex;
	}
	const handleSendName = (wifiNameObj) => {
		sendToBLE(deviceMac.value, 2, wifiNameObj, deviceOBj.value);
	}

	const handleSendPass = (wifiPassObj) => {
		setTimeout(() => {
			sendToBLE(deviceMac.value, 3, wifiPassObj, deviceOBj.value);
		}, 400);
	}

	const handleSendwifi = () => {
		setTimeout(() => {
			sendToBLE(deviceMac.value, 4, null, deviceOBj.value);
		}, 800);
	}
	watch(() => store.state.deviceMac, (v) => {
		if (v) {
			current.value = 1
		}
	}, {
		deep: true,
		immediate: true
	})
	watch(() => wififangwen.value, (v) => {
		if (v == 13 && settingTime.value == 2) {
			current.value = 2
			uni.showToast({
				icon: 'none',
				title: '型号设置成功'
			})
		}
		if (v.every(item => item === 13) && v.length === 3) {
			uni.showToast({
				title: '配网设置成功',
				icon: "none"
			})
			current.value = 3
		}
		if (v == 13 && settingTime.value == 4) {
			uni.showToast({
				title: '测试完成',
				icon: "none"
			})
			wififangwen.value = []
		}
	}, {
		deep: true,
		immediate: true
	})
</script>

<style>
	.content {
		margin: 32rpx;

		.cardTitel {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 30rpx;
			color: #000000;
			font-style: normal;
			text-transform: none;
			padding-left: 100rpx;
		}

		.cardDesc {
			padding-left: 100rpx;
			padding-top: 10rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 20rpx;
			color: #B1B1BA;
			font-style: normal;
			text-transform: none;
		}
	}

	.uv-input {
		width: 300rpx;
	}
</style>